package com.pxx.pj.pxx.service.impl;

import com.pxx.pj.common.annotation.RequiredLog;
import com.pxx.pj.common.exception.ServiceException;
import com.pxx.pj.common.pojo.PageObject;
import com.pxx.pj.common.util.ValidUitls;
import com.pxx.pj.pxx.dao.PxxLogDao;
import com.pxx.pj.pxx.pojo.PxxLog;
import com.pxx.pj.pxx.service.PxxLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class PxxLogServiceImpl implements PxxLogService {

    @Autowired
    private PxxLogDao pxxLogDao;

    @Async //此注解描述的方法为一个异步切入点方法，此方法在执行时会运行在一个独立的线程中
    @Transactional//默认为Propagation.REQUIRED
    //@Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void saveObject(PxxLog entity) {//此方法永远工作的一个独立的事务中
        String tName=Thread.currentThread().getName();
        System.out.println("SysLogServiceImpl.saveObject->thread.name->"+tName);
        //try{Thread.sleep(5000);}catch (Exception e){}//模拟耗时操作
        pxxLogDao.insertObject(entity);
    }
   // @RequiresPermissions("sys:log:delete")
    @RequiredLog("日志删除")
    @Override
    public int deleteObjects(Integer... ids) {
        //1.参数校验
        if(ids==null||ids.length==0)
            throw new IllegalArgumentException("必须提供正确的id值");
        //2.基于id删除日志
        int rows=pxxLogDao.deleteObjects(ids);
        //3.校验结果并返回
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        return rows;
    }

    @RequiredLog("日志查询")
    @Override
    public PageObject<PxxLog> findPageObjects(String username, Integer pageCurrent) {
        String tName=Thread.currentThread().getName();
        System.out.println("SysLogServiceImpl.findPageObjects->thread.name->"+tName);
        //long t1=System.currentTimeMillis();
        //1.参数校验
        if(pageCurrent==null||pageCurrent<1)throw new IllegalArgumentException("当前页码值不正确");
        //2.查询总记录数并校验
        int rowCount=pxxLogDao.getRowCount(username);
        if(rowCount==0) throw new ServiceException("没有找到对应记录");
        //3.查询当前页记录
        int pageSize=5;
        int startIndex=(pageCurrent-1)*pageSize;
        List<PxxLog> records=pxxLogDao.findPageObjects(username,startIndex, pageSize);
        PageObject<PxxLog> pageObject= new PageObject<>(rowCount,records,pageCurrent,pageSize);
        return pageObject;
    }
}
